package org.quipu.client;

import static com.google.gwt.user.client.ui.HasHorizontalAlignment.ALIGN_LEFT;
import static com.google.gwt.user.client.ui.HasVerticalAlignment.ALIGN_TOP;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Widget;
import org.quipu.client.events.AppEvent;
import org.quipu.client.events.AppEventBus;
import org.quipu.client.events.AppEventListener;
import org.quipu.client.events.BookSelectionChangedEvent;
import org.quipu.client.events.LoginEvent;

public class SettingsPanel extends AppEventWidget implements AppEventListener {

    private final HorizontalPanel hPanel;
    private final BookEditPanel booksPanel;
    private final CategoryEditPanel categoryPanel;
    private final CurrencyEditPanel currencyPanel;

    public SettingsPanel(AppEventBus eventBus, AppCache cache) {
        super(eventBus, cache);
        hPanel = new HorizontalPanel();
        hPanel.setHorizontalAlignment(ALIGN_LEFT);
        hPanel.setVerticalAlignment(ALIGN_TOP);
        hPanel.addStyleName("contentPanel");
        hPanel.addStyleName("gridPanel");
        booksPanel = new BookEditPanel(eventBus, cache);
        categoryPanel = new CategoryEditPanel(eventBus, cache);
        currencyPanel = new CurrencyEditPanel(eventBus, cache);
    }

    @Override
    public void init() {
        booksPanel.init();
        categoryPanel.init();
        currencyPanel.init();
        getEventBus().addListener(BookSelectionChangedEvent.class, this);
        getEventBus().addListener(LoginEvent.class, this);
    }

    @Override
    public void handleEvent(AppEvent event) {
        if(event != null) {
            if(event instanceof LoginEvent || event instanceof BookSelectionChangedEvent) {
                selectBook();
            }
        }
    }

    @Override
    public Widget getWidget() {
        return hPanel;
    }

    private void selectBook() {
        if(getCache().getCurrentBook() != null) {
            show();
        } else {
            hide();
        }
    }

    private void hide() {
        hPanel.clear();
        hPanel.add(booksPanel.getWidget());
    }

    private void show() {
        hPanel.clear();
        hPanel.add(booksPanel.getWidget());
        hPanel.add(categoryPanel.getWidget());
        hPanel.add(currencyPanel.getWidget());
    }
}
